package scale.data;
import java.text.DecimalFormat;
import java.util.Arrays;
import scale.sim.LocalSession;
import scale.sim.RemoteSession;
/**
 * 
 * @author Nikolaj Koehnke Jensen
 *
 */
public class Scale implements Runnable {

	private String instructionsDisplay = "";
	private double brutto = 0;
	private double tara = 0;
	private boolean isBusy = false;
	final DecimalFormat dFormat = new DecimalFormat("#.###");
	
	private LocalSession localsession;
	private RemoteSession rmCaller;
	private String rmResponse;

	public Scale() {
		// Start LocalSession
		localsession = new LocalSession(this);
		new Thread(localsession).start();
	}

	@Override
	public void run() {}
	
	/**
	 * Returns the scale response on none-RM commands
	 * @param input command
	 * @return Scale response
	 */
	public synchronized String scaleInput(String input) {

		String output = ""; // Prepare output string

		String[] inputArray = input.toUpperCase().split(" "); // Split the given input

		if (inputArray[0].equals("D")) { // Reset or set Display on weight

			if (input.toUpperCase().equals("D")) { // Reset weight display
				this.setInstructionsDisplay("");
			} else { // Set weight display
				this.setInstructionsDisplay(input.substring(2, input.length()));
			}
			localsession.setDisplay(this.instructionsDisplay);
			output = "D A";

		} else if (inputArray[0].equals("DW")) { // Return the weight display

			output = this.getInstructionsDisplay();

		} else if (inputArray[0].equals("T")) { // Pressing the Tara button

			this.setTara();
			output = "T S      " + (this.getTara()) + " kg ";

		} else if (inputArray[0].equals("S")) { // Get Netto weight
			output = "S S      " + (this.getBrutto() - this.getTara()) + " kg ";

		} else if (inputArray[0].equals("B")) { // Set Brutto weight
			if (inputArray.length > 1) {
				this.setBrutto(Double.parseDouble(inputArray[1]));
				output = "DB";

			} else {
				output = "B L";
			}

		} else if (inputArray[0].equals("Q")) { // returns empty string
			output = "";
			
		} else { // Else return ES
			output = "ES";
		}
		return output + "\r\n";
	}

	/**
	 * Returns the scale response on RM commands
	 * @param input Command
	 * @param rs Command callers RemoteSession
	 */
	public synchronized void scaleInputRM(String input, RemoteSession rs) {
		String output = "";
		
		// Split input string to command and arguments
		String temp = input.replace(" \"", "#");
		temp = temp.replace("\"", " ");
		
		String[] inputArgs = temp.split("#");
		
		for (String string : inputArgs) {
			System.out.print("["+string+"]");
		}System.out.println();
		
		String[] inputArray = inputArgs[0].toUpperCase().split(" ");


		if (!isBusy) {
			rmCaller = rs;
			if(inputArray[0].equals("RM20")){
				// IN: RM20 8 "Type in ID" "" "&3"
				// OUT: RM20 B
				// OUT: RM20 A "input" 
				System.out.println("out "+inputArgs.length+" : "+inputArgs[1]);
				if(inputArgs.length != 4){
					output = inputArray[0]+ " L";
				} else {
					if(Integer.parseInt(inputArray[1]) == 8){
						localsession.setDisplay(inputArgs[1]);
						isBusy = true;
						rmResponse = inputArray[0] + " A";
						output = inputArray[0] + " B";
					}
				}
			} 
			else if(inputArray[0].equals("RM30")){
				localsession.setSoftButton(Arrays.copyOfRange(inputArgs, 1, inputArgs.length));
				output = inputArray[0]+ " B" ;
				//IN:  RM30 "OK" "Cancel"
				//OUT: RM30 B
			}
			else if(inputArray[0].equals("RM39")){
				//IN:  RM39 1
				//OUT: RM39 A
				output = inputArray[0]+ " A";
			}
			else if(inputArray[0].equals("RM49")){
				localsession.setDisplay(inputArgs[1]);
				isBusy = true;
				rmResponse = inputArray[0] + " A";
				output = inputArray[0] + " B";
				//IN:  RM49 4 "Verify product as kogesalt"
				//OUT: RM49 B
				//OUT: RM49 A 1
			} 
			
		} else {
			output = inputArray[0] + " I";
		}

		rs.sendResponse( output + "\r\n"); // Send response
	}

	/**
	 * Sends the RM commands response to the RM Caller
	 * @param str softButton index
	 * @param displayed text
	 */
	public void rmResponse(String str, String display) {
		if (rmCaller != null && rmResponse != null) {
			String res = rmResponse;
			String out = "";
			if (res.startsWith("RM20")) {
				if (str.equals("1")) {
					out = res + " \"" + display + "\"";
				} else {
					out = "RM20 C";
				}
			} else if (res.startsWith("RM49")) {
				out = res + " " + str;
			} else {
				out = res + " " + str;
			}
			rmCaller.sendResponse(out + "\r\n");
			rmResponse = "RM30 C";
			isBusy = false;
		}
	}
	
	// GETTERS AND SETTERS
	public synchronized String getInstructionsDisplay() {
		return instructionsDisplay;
	}

	public synchronized void setInstructionsDisplay(String inDis) {
		instructionsDisplay = inDis;
	}

	public synchronized double getBrutto() {
		return new Double(dFormat.format(brutto).replaceAll(",", "."));
	}

	public synchronized void setBrutto(double brut) {
		brutto = brut;
		localsession.setBrutto(brut);
	}

	public synchronized double getTara() {
		return tara;
	}

	public synchronized void setTara() {
		tara = brutto;
		localsession.updateNetto();
	}
}
